import org.jsecurity.authc.UsernamePasswordToken
import org.jsecurity.authc.credential.CredentialsMatcher
import org.jsecurity.authc.AccountException
import org.jsecurity.authc.UnknownAccountException
import org.jsecurity.authc.SimpleAccount
import org.jsecurity.authc.IncorrectCredentialsException
import rowingmanager.domain.User

class AuthRealm {
   static authTokenClass = UsernamePasswordToken
   CredentialsMatcher credentialMatcher

   def authenticate(authToken){
      def username = authToken.username

       //Null username is invalid
       if(username == null) {
           throw new AccountException('Null usernames are not allowed by this realm')
       }

       //Get the user with the given username If the user is not found, then they don't have an account
       //and we throw an exception
       def user = User.findByEmail(username)
       if(!user){
           throw new UnknownAccountException("No account found for $username")
       }
       //Now check the user's password against the hashed value stored in the database
       def account = new SimpleAccount(username,user.password,"RowingManagementRealm")
       if(!credentialMatcher.doCredentialsMatch(authToken,account)) {
           throw new IncorrectCredentialsException("Invalid password for $username")
       }
       return account
   }
}       